package com.icesoft.base.manager.base;

import com.icesoft.base.manager.config.UrlConstant;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.web.helper.PathUtil;
import com.icesoft.core.web.helper.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author XHH
 */
public abstract class BaseExportController<D>  {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	public abstract BaseExportAction<D> getExportAction();

	/**
	 * 导出查询条件
	 */
	public abstract List<D> findSelect(HttpServletRequest request);

	/**
	 * 导出文件名
	 */
	public String getExportFileName() {
		return "导出数据";
	}

	/**
	 * 暂时只支持xls类型的导出
	 **/

	@GetMapping(UrlConstant.EXPORT)
	protected void exportMapping(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = appendExt(getExportFileName());
		fileName = fileName.replace(".xlsx", ".xls");
		List<D> models = findSelect(request);
		BaseExportAction<D> exportAction = getExportAction();
		List<Map<String, String>> result = exportAction.toMaps(models);
		String outPath = getExcelRootPath() + "export/" + UUID.randomUUID().toString() + ".xls";
		log.debug("导出excel保存路径：{}", outPath);
		exportAction.writeToExcel(result, outPath);
		try {
			ResponseUtils.writeToFileStream(response, fileName, new FileInputStream(outPath));
		} catch (IOException e) {
			log.error("excel文件下载错误", e);
			ResponseUtils.writeJson(response, Resp.error("文件读取错误"));
		}
	}

	public final String getExcelRootPath() {
		return PathUtil.getRootUploadPath() + "excel/";
	}

	private String appendExt(String fileName) {
		if (!StringUtils.contains(fileName, ".")) {
			fileName += ".xls";
		}
		return fileName;
	}
}
